import React, { PureComponent } from 'react';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import { Spin, Tag, Menu, Icon, Avatar, notification } from 'antd';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import IconFont from '@/components/IconFont';
import {
  l1ManualDocUrl,
  l2ManualDocUrl,
  l3ManualDocUrl,
  webUrl,
  cardReaderDrivenUrl,
} from '@/defaultSettings';

export default class RightContent extends PureComponent {
  constructor(props) {
    super(props);
  }

  openNotificationWithIcon = ({ type, message = '', description = '' }) => {
    notification[type]({
      message,
      description,
    });
  };

  /**
   * 显示操手册
   */
  handleShowManualClick = () => {
    const { currentUser } = this.props;
    const { roles } = currentUser;
    // 检查是否包含ROLE_ADMIN
    const isAdmin = roles ? roles.some(item => item === 'ROLE_ADMIN') : false;
    // 是否是机构用户
    const isOrganizationUser = roles ? roles.some(item => item === 'ROLE_MANAGER') : false;
    if (isAdmin) {
      window.open(l1ManualDocUrl);
    } else if (isOrganizationUser) {
      window.open(l2ManualDocUrl);
    } else {
      window.open(l3ManualDocUrl);
    }
  };

  getNoticeData() {
    const { notices = [] } = this.props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag color={color} style={{ marginRight: 0 }}>
            {newNotice.extra}
          </Tag>
        );
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }

  getUnreadData = noticeData => {
    const unreadMsg = {};
    Object.entries(noticeData).forEach(([key, value]) => {
      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }
      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter(item => !item.read).length;
      }
    });
    return unreadMsg;
  };

  componentDidMount() {}

  render() {
    //console.log(this.props.currentUser);
    const { currentUser, fetchingNotices, onNoticeVisibleChange, onMenuClick, theme } = this.props;
    const { roles } = currentUser;
    // 检查是否包含ROLE_ADMIN
    const isAdmin = roles ? roles.some(item => item === 'ROLE_ADMIN') : false;
    // 检查是否包含ROLE_AHCDC
    const isAhCdc = roles ? roles.some(item => item === 'ROLE_AHCDC') : false;
    // 是否是机构用户
    const isOrganizationUser = roles ? roles.some(item => item === 'ROLE_DEV') : false;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        {/*用户信息修改*/}
        {/*<Menu.Item key="userinfo">
         <Icon type="setting" />
         <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
         </Menu.Item>
         <Menu.Divider />*/}
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
        </Menu.Item>
      </Menu>
    );
    const { onHandlePage } = this.props.location;
    const noticeData = this.getNoticeData();
    const unreadMsg = this.getUnreadData(noticeData);
    let className = styles.right;
    if (theme === 'dark') {
      className = `${styles.right}  ${styles.dark}`;
    }
    return (
      <div className={className}>
        {/*操作手册*/}
        {/* <span
          onClick={() => {
            this.handleShowManualClick();
            // this.openNotificationWithIcon({
            //   type: 'info',
            //   message: '操作手册',
            //   description: '😂还在开发中，稍等片刻，一会更新',
            // });
          }}
          style={{ marginRight: '16px', cursor: 'pointer' }}
        >
          <IconFont type="icon-bangzhuzhongxin" style={{ marginRight: '4px' }} />
          操作手册
        </span> */}

        <a
          style={{ marginRight: '16px', cursor: 'pointer', color: '#fdfdfd' }}
          href={`${cardReaderDrivenUrl}`}
          download="新中新webapi读卡服务3.3.4.zip"
        >
          <Icon type="download" style={{ marginRight: '4px' }} />
          读卡器驱动
        </a>

        {/*数据看板*/}
        {isAdmin || isAhCdc ? (
          <span
            onClick={() => {
              window.open(`${webUrl}/ds/datascreen`);
            }}
            style={{ marginRight: '16px', cursor: 'pointer' }}
          >
            <Icon type="area-chart" style={{ marginRight: '4px' }} />
            数据看板
          </span>
        ) : null}

        {currentUser.nickname ? (
          <HeaderDropdown overlay={menu}>
            <span className={`${styles.action} ${styles.account}`}>
              <IconFont
                type={'icon-yonghu'}
                style={{ fontSize: '18px', marginRight: '8px' }}
              ></IconFont>
              <span className={styles.name}>{currentUser.nickname}</span>
              <span className={styles.name}>{`(${currentUser.orgName})`}</span>
              {/*如果是机构用户显示该用户所属机构*/}
              {/*{isOrganizationUser ? (*/}
              {/*  <span className={styles.name}>{`(${currentUser.orgName})`}</span>*/}
              {/*) : null}*/}
            </span>
          </HeaderDropdown>
        ) : (
          <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
        )}
        {/*多语言*/}
        {/*<SelectLang className={styles.action} />*/}
      </div>
    );
  }
}
